package com.quickcode.example.juc;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * 异步线程执行方法逻辑
 */
@Slf4j
public class CompletableFutureExample1 {

    public static final ExecutorService EXECUTORSERVICE = Executors.newCachedThreadPool();


    public static void main(String[] args) throws InterruptedException {
        /*异步执行，无返回*/
        CompletableFuture<Void> completableFuture1 = CompletableFuture.runAsync(new Runnable() {
            @Override
            public void run() {
                System.out.println("开始进行异步执行");
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    log.error("线程中断");
                }
            }
        }, EXECUTORSERVICE);

        completableFuture1.whenComplete(new BiConsumer<Void, Throwable>() {
            @Override
            public void accept(Void aVoid, Throwable throwable) {
                System.out.println("completableFuture1执行完成，完成回调逻辑执行");
            }
        });

        /*异步执行，有返回*/
        CompletableFuture<Integer> completableFuture2 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
            @Override
            public Integer get() {
                return 1 + 1;
            }
        }, EXECUTORSERVICE);

        completableFuture2.whenComplete(new BiConsumer<Integer, Throwable>() {
            @Override
            public void accept(Integer integer, Throwable throwable) {
                System.out.println("integer:" + integer);
            }
        });

        completableFuture2.exceptionally(new Function<Throwable, Integer>() {
            @Override
            public Integer apply(Throwable throwable) {
                log.error("异常：{}",throwable);
                return 0;
            }
        });

        TimeUnit.SECONDS.sleep(10);

    }
}